package com.hb.medical_research_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.medical_research_system.common.Results;
import com.hb.medical_research_system.entity.Result;
import com.hb.medical_research_system.service.ResultService;
import com.hb.medical_research_system.mapper.ResultMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author hb
* @description 针对表【result】的数据库操作Service实现
* @createDate 2023-02-25 11:14:59
*/
@Slf4j
@Service
public class ResultServiceImpl extends ServiceImpl<ResultMapper, Result> implements ResultService{

    //TODO 2001代表无新增结果, 2002代表有新增结果

    @Autowired
    private ResultMapper resultMapper;

    @Override
    public Results add(Result result) {
        resultMapper.insert(result);
        return Results.info(Results.SUCCESS,"结果插入成功");
    }

    @Override
    public Results check(Result result) {


        LambdaQueryWrapper<Result> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Result::getArticleId, result.getArticleId())
                          .eq(Result::getKeyword, result.getKeyword());

        log.info(result.toString());


        //查询是否已经有该结果
        Result realresult = resultMapper.selectOne(lambdaQueryWrapper);

        //若无,则添加新结果,修改该结果数据
        if(realresult == null){

            resultMapper.insert(result);

            return Results.info(Results.INSERT_NEW,"无该结果,新增该结果");
        }
        //若已经有该结果,修改该结果数据
        else {

            LambdaUpdateWrapper<Result> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Result::getResultId, result.getResultId())
                    .set(Result::getLikes, realresult.getLikes()+result.getLikes())
                    .set(Result::getUnlikes, realresult.getUnlikes()+result.getUnlikes())
                    .set(Result::getClick, realresult.getClick()+result.getClick());
            resultMapper.update(null,updateWrapper);

            return Results.info(Results.INSERT_OLD, "已有该结果,已修改结果");

        }
    }

}




